<script setup>
import { ref, computed, onMounted, nextTick } from 'vue';
import { SearchOutlined, CloseOutlined, SmileOutlined, PictureOutlined } from '@ant-design/icons-vue';
import { useChatStore } from '../../piniaStore/pinia.js';

const chatStore = useChatStore();

const props = defineProps({
  visible: Boolean
});

const emit = defineEmits(['update:visible']);

const handleClose = () => {
  emit('update:visible', false);
};

// 搜索好友列表的搜索框
const searchText = ref('');
// 当前选中的联系人
const selectedContact = ref(null);
const inputMessage = ref('');
const messageContainer = ref(null);

// 在线用户数据源
const contactGroups = ref({
  online: {
    title: '在线用户',
    contacts: []
  }
});

// 从 Pinia Store 获取状态
const onlineUsers = computed(() => chatStore.onlineUsers);
const messages = ref([]);
const targetUser = ref(null);

const updateOnlineUsers = (users) => {
  contactGroups.value.online.contacts = users.map((user, index) => ({
    id: index + 1,
    name: user,
    avatar: 'https://ai-public.mastergo.com/ai/img_res/325b06f6bd14f02d459d8c34d6b402a5.jpg',
    online: true,
    lastMessage: '',
    lastTime: '',
    unread: 0
  }));
};

const selectContact = (contact) => {
  selectedContact.value = contact;
  targetUser.value = contact.name;
  messages.value = chatStore.getChatHistory(contact.name);
};

// 发送消息
const sendMessage = () => {
  if (!inputMessage.value.trim() || !selectedContact.value) return;

  const newMessage = {
    content: inputMessage.value.trim(),
    isSelf: true,
    time: new Date().toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' }),
  };

  messages.value.push(newMessage);
  chatStore.sendMessageToServer(inputMessage.value, selectedContact.value.name);

  inputMessage.value = '';

  nextTick(() => {
    if (messageContainer.value) {
      messageContainer.value.scrollTop = messageContainer.value.scrollHeight;
    }
  });
};

const receiveMessage = (message, fromContact) => {
  if (selectedContact.value && selectedContact.value.name === fromContact) {
    const newMessage = {
      content: message,
      isSelf: false,
      time: new Date().toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' }),
    };

    messages.value.push(newMessage);

    nextTick(() => {
      if (messageContainer.value) {
        messageContainer.value.scrollTop = messageContainer.value.scrollHeight;
      }
    });
  } else {
    const contact = contactGroups.value.online.contacts.find(c => c.name === fromContact);
    if (contact) {
      contact.unread = (contact.unread || 0) + 1;
      contact.lastMessage = message;
      contact.lastTime = new Date().toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
    }
  }
};

onMounted(() => {
  chatStore.$subscribe((mutation, state) => {
    if (mutation.type === 'receiveMessage') {
      const { message, from } = mutation.payload;
      receiveMessage(message, from);
    }
    if (mutation.type === 'updateOnlineUsers') {
      updateOnlineUsers(mutation.payload);
    }
  });

  updateOnlineUsers(chatStore.onlineUsers);
});
</script>
